const channelModel = require("../../model/channel");
const {parseString} = require("xml2js");
const sip = require("sip");
const log4js = require('../../data/log');
const logger = log4js.getLogger('sip');

const dbHandler = require('../../pipe/dbhandler');
const keepaliveHandler = require('./messages/keepaliveHandler');
const catalogHandler = require('./messages/catalogHandler');
const deviceInfoHandler = require('./messages/deviceInfoHandler');
const deviceModel = require('../../model/device');

/**
 * 收到 message 后的处理
 * @type {{handle: ((function(*, *): Promise<void>)|*)}}
 */
module.exports = {
    handle: async (deviceId, rq) => {
        const deviceInfo = await dbHandler.loadDevice(deviceId);
        if (!deviceInfo) {
            logger.info(`[接收消息处理] 需要等待设备重新register：deviceId=${deviceId}`);
        } else {
            if (rq.content) {
                // 收到其它消息
                parseString(rq.content, async (err, result) => {
                    if (result.Notify) {
                        let CmdType = result.Notify.CmdType[0];
                        switch (CmdType) {
                            case 'Keepalive':
                                // 心跳
                                await keepaliveHandler.handle(rq, deviceId, result.Notify.DeviceID);
                                break;
                            case 'Catalog':
                                // 定时刷新catalog状态
                                let deviceIds = result.Notify.DeviceID;
                                logger.info('[目录更新] Notify=', result.Notify);
                                for (let s in deviceIds) {
                                    // 编码转换
                                    channelModel.updateDeviceInfo(deviceIds[s]).catch((e) => {
                                        logger.error(e);
                                    });
                                }
                                sip.send(sip.makeResponse(rq, 200, 'OK'));
                                break;
                            case 'Alarm':
                                logger.info(`[报警处理] deviceId=${deviceId}, via0=`, rq.headers.via[0]);
                                let alarmRet = sip.makeResponse(rq, 200, 'OK');
                                sip.send(alarmRet);

                                break;
                            default:
                                logger.warn('未支持的指令', CmdType, result);
                        }
                    } else if (result.Response) {
                        if (!deviceInfo) {
                            logger.error(`未注册成功,deviceId=${deviceId}, result=`, result);
                        } else {
                            let CmdType = result.Response.CmdType.toString();
                            sip.send(sip.makeResponse(rq, 200, 'OK'));

                            if (!deviceInfo.channels) {
                                deviceInfo.channels = {};
                            }
                            switch (CmdType) {
                                case "DeviceInfo":
                                    await deviceInfoHandler.handle(deviceInfo, result.Response);
                                    break;
                                case "Catalog":
                                    logger.info('[目录更新] deviceInfo.DeviceID=', deviceInfo.DeviceID);
                                    catalogHandler.handle(deviceInfo, result.Response);
                                    await deviceModel.update(deviceInfo);
                                    break;
                                default:
                                    logger.error("CmdType 尚不支持", CmdType);
                                    break;
                            }
                        }
                    }
                });
            } else {
                logger.warn(`deviceId=${deviceId} rq.content为空，无法解析，目前遇到的情况有设备是不支持Catalog，所以这里创建子通道,rq=`, rq);
                deviceInfo.sumnum = '1';
                let temp1 = {
                    Name: [''],
                    Manufacturer: [''],
                    Model: [''],
                    Owner: [''],
                    CivilCode: [''],
                    Address: [''],
                    RegisterWay: ['1'],
                    Secrecy: ['0'],
                    ParentID: [deviceId],
                    DeviceID: [deviceId]
                };

                let channelId = deviceId;

                if (!deviceInfo.channels) {
                    deviceInfo.channels = {};

                    deviceInfo.channels[channelId] = deviceModel.generateEmptyChannel(deviceInfo, channelId);

                    if (!deviceInfo.channels[channelId].uri) {
                        logger.warn(`检查这里的逻辑.deviceId=${deviceId}, channelId=${channelId}`, deviceInfo.channels[channelId]);
                    } else {
                        // deviceInfo.channels[channelId].uri=deviceInfo.channels[channelId].uri;
                    }
                    deviceInfo.channels[channelId].parentid = deviceId;

                    await channelModel.updateDeviceInfo(temp1);
                }
            }
        }
    }
}
